from exts import db
from flask import Blueprint, request, render_template, url_for, redirect
from score.model import Score


score = Blueprint('score', __name__);

# 分数列表
@score.route('score_list', methods=['GET', 'POST'])
def score_list():
    score_list = Score.query.all()
    return render_template('score_list.html', score_list=score_list)
    
# 根据学号搜索
@score.route('/score/search', methods=['GET', 'POST'])
def search():
    keyword = request.args.get('keyword')
    score_list = Score.query.filter(
        Score.number.like('%{keyword}%'.format(keyword=keyword))
    ).all()
    return render_template('score_list.html', score_list=score_list)

# 删除
@score.route('/score/remove', methods=['GET', 'POST'])
def remove():
    id = request.args.get('id')
    score = Score.query.filter(
        Score.id == id
    ).first()
    db.session.delete(score)
    db.session.commit()
    return redirect(url_for('score.score_list'))

# 分数详情，更新，添加
@score.route('/score/edit', methods=['GET', 'POST'])
def edit():
    if request.method=='GET':
        id = request.args.get('id')
        option = request.args.get('option')
        score = Score.query.filter(
            Score.id == id
        ).first()
        if option == 'detail':
            return render_template('score_editor.html', score=score)
        else:
            return render_template('score_editor.html', score=score, update=True)
    else:
        id = request.form.get('id')
        name = request.form.get('name')
        number = request.form.get('number')
        subject = request.form.get('subject')
        grade = request.form.get('grade')

        score = Score.query.filter(
            Score.id == id
        ).first()
        if score is None:
            score = Score(name=name, number=number,subject=subject,grade=grade)
            db.session.add(score)
            db.session.commit()
        else:
            score.name= name
            score.number = number
            score.subject = subject
            score.grade= grade
            db.session.commit()
        return redirect(url_for("score.score_list"))